﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace KC.ExtensionMethods
{
	/// <summary>Extension methods on URIs</summary>
	public static class URI
	{
		/// <summary>Gets the root domain of any URI</summary>
		/// <param name="uri">URI to get root domain of</param>
		/// <returns>Root domain with TLD</returns>
		public static string GetRootDomain(this System.Uri uri)
		{
			if (uri == null)
				throw new ArgumentNullException("uri");

			string Domain = uri.Host;
			while (Domain.CountOf('.') > 1)
				Domain = Domain.Substring(Domain.IndexOf('.') + 1);
			return Domain;
		}
		/// <summary>Determines whether a uri is from a given domain.</summary>
		/// <param name="uri">uri in question</param>
		/// <param name="domain">domain to determine whether the uri is part of</param>
		/// <returns>True = uri is from domain; false = uri is not from domain</returns>
		public static bool isFromDomain(this Uri uri, string domain)
		{
			if (uri == null)
				throw new ArgumentNullException("uri");
			if (string.IsNullOrEmpty(domain))
				throw new ArgumentNullException("domain");

			while (domain.Contains("://"))
				domain = domain.Substring(domain.IndexOf("://") + 3);
			domain = "http://" + domain;

			try { return uri.GetRootDomain().ToLower() == new Uri(domain).GetRootDomain().ToLower(); }
			catch { return false; }
		}
		/// <summary>Determines whether a domain is one of my domains or a subdomain thereof.</summary>
		/// <param name="uri">URI to determine the mineness of</param>
		/// <returns>Flag true = mine; false = not mine</returns>
		public static bool isMyDomain(this Uri uri)
		{
			if (uri == null) throw new ArgumentNullException("uri");
			string domain = uri.GetRootDomain().ToLower().Trim();
			try { domain = new Uri("http://" + domain).GetRootDomain(); }
			catch (UriFormatException) { return false; }
			foreach (string myDomain in KC.Overhead.Constants.Domains.MyDomains)
				if (domain == myDomain.ToLower().Trim()) return true;
			return false;
		}
	}
}
